package com.wyg.ep_timer.phoenix;

import com.wyg.ep_timer.entity.Article;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Description: 需要解决的问题：① 多线程query
 * ② kafka消费失败问题
 * ③ 多线程协同问题
 * ④ 已消费id存储保存问题
 *
 * @author WangYongGan
 * @since 2022/5/31 13:29
 */
@Component
public class Query {
    public static ThreadLocal<Connection> cons = new ThreadLocal<>();

    @SneakyThrows
    public Connection getConnect() {
        if (cons.get() == null) {
            cons.set(DriverManager.getConnection("jdbc:phoenix:w2:2181"));
        }
        return cons.get();
    }

    public void main(String[] args) {
        final List<Article> articles = articleFromPhoenix(Arrays.asList(1, 2, 5001));
        System.out.println("===");
    }

    @SneakyThrows
    public List<Article> articleFromPhoenix(List<Integer> list) {
        final Connection con = getConnect();
        StringBuilder sql = new StringBuilder("select * from article where id in(?");
        for (int i = 0; i < list.size() - 1; i++) {
            sql.append(",?");
        }
        sql.append(")");
        PreparedStatement ps = con.prepareStatement(sql.toString());
        for (int i = 0; i < list.size(); i++)
            ps.setInt(i + 1, list.get(i));
        final ResultSet resultSet = ps.executeQuery();
        List<Article> res = new ArrayList<>();
        while (resultSet.next()) {
            Article article = new Article();
            article.setId(String.valueOf(resultSet.getInt("id")));
            article.setRawText(resultSet.getString("raw_text"));
            article.setTitle(resultSet.getString("title"));
            article.setCreatedAt(resultSet.getDate("create_at"));
            article.setScheme(resultSet.getString("scheme"));
            article.setSource(resultSet.getString("source"));
            article.setPlatform(resultSet.getString("platform"));
            res.add(article);
        }
        return res;
    }
}
